package com.shuyuansystem.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shuyuansystem.dao.CheckRoleMapper;
import com.shuyuansystem.entity.Result;
import com.shuyuansystem.pojo.OrderInfo;
import com.shuyuansystem.pojo.OrderList;
import com.shuyuansystem.pojo.Token;
import com.shuyuansystem.pojo.User;
import com.shuyuansystem.service.OrderInfoService;
import com.shuyuansystem.service.OrderListService;
import com.shuyuansystem.utils.JWTUtils;
import com.shuyuansystem.utils.QiniuUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/BusinessOrder")
public class BusinessOrderController {
    private static final Logger logger = LoggerFactory.getLogger(BusinessOrderController.class);
    @Autowired
    private OrderListService orderListService;
    @Autowired
    private CheckRoleMapper checkRoleMapper;
    @Autowired
    private OrderInfoService orderInfoService;
    //导入User类，便于接收前端的角色数据
    User user = new User();

    @GetMapping("/getRoleAndUserId")
    public User getRoleAndUserId(@RequestHeader("Authorization") String token) {
        Map<String, Object> response = new HashMap<>();
        try {
            // 去除 Bearer 前缀
            token = token.replace("Bearer ", "");
            // 从 Token 中获取用户 ID
            String userId = JWTUtils.getUserIdFromToken(token);
            if (userId == null) {
                response.put("success", false);
                response.put("message", "无法从 Token 中获取用户 ID");
                return null;
            }
            // 根据用户 ID 查询角色
            String role = checkRoleMapper.checkRoleById(userId);
            if (role == null) {
                response.put("success", false);
                response.put("message", "未找到该用户的角色信息");
                return null;
            }

            user.setId(Integer.parseInt(userId));
            user.setRole(role);
            response.put("userId", userId);
            response.put("role", role);
            response.put("success", true);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "处理请求时发生错误: " + e.getMessage());
        }
        return user;
    }
    @GetMapping("/getOrderList")
    public List<Map<String, Object>> getOrderList(@RequestParam("userId") String userId) {
        String merchantId = userId;
        List<OrderInfo> orderInfos = orderInfoService.getAllByMerchantId(merchantId);
        List<String> merchantOrderNumbers = new ArrayList<>();
        for (OrderInfo orderInfo : orderInfos) {
            if (orderInfo.getMerchantOrderNumber() != null) {
                merchantOrderNumbers.add(orderInfo.getMerchantOrderNumber());
            }
        }
        List<OrderList> orderLists = orderListService.getByMerchantOrderNumbers(merchantOrderNumbers);
        Map<String, List<OrderList>> integratedMap = new HashMap<>();
        for (OrderList orderList : orderLists) {
            String merchantOrderNumber = orderList.getMerchant_order_number();
            integratedMap.computeIfAbsent(merchantOrderNumber, k -> new ArrayList<>()).add(orderList);
        }
        List<Map<String, Object>> result = new ArrayList<>();
        for (OrderInfo orderInfo : orderInfos) {
            String merchantOrderNumber = orderInfo.getMerchantOrderNumber();
            Map<String, Object> orderData = new HashMap<>();
            orderData.put("用户 ID", orderInfo.getUserId());
            orderData.put("商家 ID", orderInfo.getMerchantId());
            orderData.put("收货地址", orderInfo.getShippingAddress());
            orderData.put("电话", orderInfo.getReceiverPhone());
            orderData.put("备注", orderInfo.getRemark());
            orderData.put("总价格", orderInfo.getTotalPrice());
            // 直接返回交易状态
            orderData.put("交易状态", orderInfo.getTransactionStatus());
            // 直接返回订单状态
            orderData.put("订单状态", orderInfo.getOrderStatus());
            orderData.put("订单号", merchantOrderNumber);
            orderData.put("制作视频", orderInfo.getVideoUrl());

            List<OrderList> relatedOrderLists = integratedMap.get(merchantOrderNumber);
            if (relatedOrderLists != null) {
                List<Map<String, Object>> orderListDetails = new ArrayList<>();
                for (OrderList orderList : relatedOrderLists) {
                    Map<String, Object> orderListDetail = new HashMap<>();
                    orderListDetail.put("商品名称", orderList.getProduct_name());
                    orderListDetail.put("数量", orderList.getQuantity());
                    orderListDetail.put("总价格", orderList.getTotal_price());
                    orderListDetails.add(orderListDetail);
                }
                orderData.put("订单详情", orderListDetails);
            }
            result.add(orderData);
        }
        return result;
    }
    @PostMapping("/toProduct")
    public Result toProduct(@RequestBody Map<String, String> requestBody) {
        try {
            // 获取前端传递的商家订单号
            String merchantOrderNumber = requestBody.get("merchantOrderNumber");
            logger.info("接收到的商家订单号: {}", merchantOrderNumber);

            // 验证订单号是否为空
            if (merchantOrderNumber == null || merchantOrderNumber.trim().isEmpty()) {
                logger.error("商家订单号为空，无法处理请求");
                return new Result(false, "商家订单号不能为空");
            }

            // 调用服务层方法更新订单状态
            boolean success = orderInfoService.updateOrderStatusToProducing(merchantOrderNumber);
            if (success) {
                logger.info("订单号 {} 已成功更新为生产中", merchantOrderNumber);
                return new Result(true, "订单生产中");
            } else {
                logger.error("订单号 {} 更新订单状态失败", merchantOrderNumber);
                return new Result(false, "更新订单状态失败，请检查订单号是否正确");
            }
        } catch (Exception e) {
            logger.error("处理请求时发生错误: ", e);
            return new Result(false, "处理请求时发生错误: " + e.getMessage());
        }
    }
    @RequestMapping("/toTransacte")
    public Result toTransacte(@RequestBody Map<String, String> requestBody) {
        try {
            // 获取前端传递的商家订单号
            String merchantOrderNumber = requestBody.get("merchantOrderNumber");
            logger.info("接收到的商家订单号: {}", merchantOrderNumber);

            // 验证订单号是否为空
            if (merchantOrderNumber == null || merchantOrderNumber.trim().isEmpty()) {
                logger.error("商家订单号为空，无法处理请求");
                return new Result(false, "商家订单号不能为空");
            }

            // 调用服务层方法更新订单状态为“订单运输中”
            boolean success = orderInfoService.updateTransactionStatusToShipping(merchantOrderNumber);
            if (success) {
                logger.info("订单号 {} 已成功更新为订单运输中", merchantOrderNumber);
                return new Result(true, "订单运输中");
            } else {
                logger.error("订单号 {} 更新订单状态失败", merchantOrderNumber);
                return new Result(false, "更新订单状态失败，请检查订单号是否正确");
            }
        } catch (Exception e) {
            logger.error("处理请求时发生错误: ", e);
            return new Result(false, "处理请求时发生错误: " + e.getMessage());
        }
    }
    @RequestMapping("/endOrder")
    public Result endOrder(@RequestBody Map<String, String> requestBody) {
        try {
            // 获取前端传递的商家订单号
            String merchantOrderNumber = requestBody.get("merchantOrderNumber");
            logger.info("接收到的商家订单号: {}", merchantOrderNumber);

            // 验证订单号是否为空
            if (merchantOrderNumber == null || merchantOrderNumber.trim().isEmpty()) {
                logger.error("商家订单号为空，无法处理请求");
                return new Result(false, "商家订单号不能为空");
            }

            // 调用服务层方法更新订单状态为“订单已完成”
            boolean success = orderInfoService.updateOrderStatusToCompleted(merchantOrderNumber);
            if (success) {
                logger.info("订单号 {} 已成功更新为订单已完成", merchantOrderNumber);
                return new Result(true, "订单已完成");
            } else {
                logger.error("订单号 {} 更新订单状态失败", merchantOrderNumber);
                return new Result(false, "更新订单状态失败，请检查订单号是否正确");
            }
        } catch (Exception e) {
            logger.error("处理请求时发生错误: ", e);
            return new Result(false, "处理请求时发生错误: " + e.getMessage());
        }
    }
    @PostMapping("/uploadToQiniu")
    public Result uploadToQiniu(@RequestParam("file") MultipartFile file, @RequestParam("orderNumber") String orderNumber) {
        try {
            // 生成文件名，这里简单用订单号和原文件名拼接
            String fileName = orderNumber + "_" + file.getOriginalFilename();
            // 调用七牛云工具类上传文件
            String videoUrl = QiniuUtils.upload2Qiniu(file.getBytes(), fileName);
            if (videoUrl != null) {
                // 调用服务层方法更新 video_url 字段
                boolean success = orderInfoService.updateVideoUrl(orderNumber, videoUrl);
                if (success) {
                    return new Result(true, "文件上传成功，video_url 更新成功");
                } else {
                    return new Result(false, "文件上传成功，但 video_url 更新失败");
                }
            } else {
                return new Result(false, "文件上传失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, "文件上传失败: " + e.getMessage());
        }
    }

    @GetMapping("/getvideourls/{MerchantOrderNumber}")
    public List<String> getVideoUrlsByMerchantOrderNumber(@PathVariable String MerchantOrderNumber) {
        return orderInfoService.getVideoUrlsByMerchantOrderNumber(MerchantOrderNumber);
    }

}